package com.example.vueback.config;


import com.example.vueback.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.从请求头中获取 token 和 username
        String username = request.getHeader("username");
        String token = request.getHeader("token");
        if(!StringUtils.hasLength(username) || !StringUtils.hasLength(token)) {
            response.sendRedirect("#/login");
            response.setStatus(403);
            return false;
        }
        //2.从 redis 上获取 token
        String redisToken = redisTemplate.opsForValue().get(username);
        //3.验证 Token 数据
        if(redisToken == null || !JwtUtils.checkToken(redisToken)) {
            response.setStatus(403);
            return false;
        }
        return true;
    }

}
